<template>
  <div>
    <!--    查询功能-->
    <div class="center">
      <div class="profiletwo">
        <el-input
          style="width: 200px"
          v-model="queryVo.value"
          @keyup.enter.native="getNoticeListhh()"
          ref="myInput"
          placeholder="请输入关键字搜索"
        ></el-input>
        <el-button
          type="primary"
          style="margin-left: 5px; height: 31.5px"
          icon="el-icon-search"
          @click="getNoticeListhh()"
          >查询</el-button
        >
      </div>

      <!-- 新增学习资料按钮 -->
      <el-button
        style="margin-left: 10px; height: 32px"
        @click="mod(1)"
        type="success"
        >新增</el-button
      >
    </div>

    <!--    列表展示-->
    <el-table
      :data="noticeData"
      :header-cell-style="{ background: '#D3D3D3FF', color: '#555555' }"
    >
      <el-table-column prop="id" label="id" width="200" header-align="center">
      </el-table-column>
      <el-table-column
        prop="title"
        label="公告标题"
        width="400"
        header-align="center"
      >
      </el-table-column>
      <el-table-column label="公告图" width="150" header-align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 150px; height: 50px"
            :src="scope.row.image"
            fit="contain"
            :preview-src-list="[scope.row.image]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="content"
        label="内容"
        width="150"
        header-align="center"
        style="display: flex; justify-content: center"
      >
        <template slot-scope="scope">
          <el-button @click="inDetail(scope.row.content)"
            >点击查看详细</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        prop="isTop"
        label="是否置顶"
        width="80"
        header-align="center"
      >
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.isTop === true ? 'success' : 'danger'"
            disable-transitions
            >{{ scope.row.isTop === true ? "已置顶" : "未置顶" }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        prop="gmtCreate"
        label="创建时间"
        width="140"
        header-align="center"
      >
      </el-table-column>
      <el-table-column prop="operate" label="操作" header-align="center">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="mod(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除此学习资料吗？"
            @confirm="deleteNotice(scope.row.id)"
            style="margin-left: 5px"
          >
            <el-button slot="reference" size="small" type="danger"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页  -->
    <div class="pagination-wrapper">
      <div class="pagination-container">
        <el-pagination
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="5"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      title="公告信息"
      :visible.sync="centerDialogVisible"
      width="75%"
      center
      :before-close="handleClose"
    >
      <!--      新增或者修改公告信息表单-->
      <el-form ref="form" :model="announcement" label-width="120px">
        <el-form-item label="置顶">
          <el-switch v-model="announcement.isTop" />
        </el-form-item>

        <el-form-item label="公告标题" prop="title">
          <el-col :span="15">
            <el-input
              v-model="announcement.title"
              placeholder="请输入公告标题"
            ></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="公告封面图片">
          <el-upload
            name="file"
            class="avatar-uploader"
            :action="actionUrl"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :data="uploadData"
            :headers="headers"
          >
            <img
              v-if="announcement.image"
              :src="announcement.image"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="富文本编辑">
          <quill-editor
            v-model="announcement.content"
            theme="snow"
            content-type="html"
            :options="editorOption"
            ref="myQuillEditor"
          >
          </quill-editor>
          <div style="display: none">
            <el-upload
              class="quill-upload"
              :on-remove="handleRemove"
              :on-success="quillSuccess"
              :action="actionUrl"
              drag
              multiple
              :data="uploadData"
              name="file"
              :headers="headers"
              :limit="5"
              :file-list="fileList"
            >
              <el-button
                id="uploadmmmmm"
                class="qqupload"
                size="small"
                type="primary"
                >点击上传</el-button
              >
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="公告详细信息"
      :visible.sync="inDetailDialogVisible"
      width="70%"
      center
    >
      <div v-html="postDetails"></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="inDetailDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getNoticeList,
  deleteNotice,
  newNotice,
  updateNotice,
} from "@/api/noticeService";
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

export default {
  components: {
    quillEditor,
  },
  name: "noticeManagement",
  data() {
    return {
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"], // toggled buttons
              ["blockquote", "code-block"],

              [{ header: 1 }, { header: 2 }], // custom button values
              [{ list: "ordered" }, { list: "bullet" }],
              [{ script: "sub" }, { script: "super" }], // superscript/subscript
              [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
              [{ direction: "rtl" }], // text direction

              [{ size: ["small", false, "large", "huge"] }], // custom dropdown
              [{ header: [1, 2, 3, 4, 5, 6, false] }],

              [{ color: [] }, { background: [] }], // dropdown with defaults from theme
              [{ font: [] }],
              [{ align: [] }],
              ["image"],
              ["clean"], // remove formatting button
            ],
            handlers: {
              // 重写点击组件上的图片按钮要执行的代码
              image: this.uploadimage,
            },
          },
        },
      },

      hh: 11,

      fileList: [],
      uploadData: {
        bucketName: "activity", // 上传头像时的附加参数
      },
      headers: {},
      actionUrl: "http://42.194.233.38:8222/minioservice/minio-upload/upload",
      onloadfile: 1,
      announcement: {
        id: "",
        title: "",
        content: "",
        image: "",
        clubId: "",
        isTop: false,
      },
      centerDialogVisible: false,
      inDetailDialogVisible: false,
      id: "",
      queryVo: {
        value: "",
      },
      page: 1,
      limit: 5,
      total: 0,
      noticeData: [],
      postDetails: "",
    };
  },
  methods: {
    //上传封面图片
    handleCoverSuccess(res, file) {
      console.log(res);
      console.log(file);
      this.announcement.image = URL.createObjectURL(file.raw);
    },
    uploadimage() {
      const uploadButton = document.querySelector("#uploadmmmmm");
      if (uploadButton) {
        uploadButton.click();
      } else {
        console.log("无法找到el-upload的上传按钮");
      }
    },

    quillSuccess(response) {
      if (response) {
        // 获取文本编辑器
        const quill = this.$refs.myQuillEditor.quill;

        // 确保获得的光标位置有效
        const range = quill.getSelection();
        if (range) {
          const pos = range.index;
          // 插入图片到光标位置
          quill.insertEmbed(pos, "image", response.data.url);
          // 使用 setTimeout 来确保编辑器更新
          setTimeout(() => {
            // 选中光标位置后，更新光标
            quill.setSelection(pos + 1); // 更新光标位置到插入后
          }, 0);
        } else {
          console.error("光标未找到");
        }
      } else {
        this.$message.error("图片插入失败");
      }
    },

    // 失去焦点事件
    onEditorBlur(quill) {
      console.log("editor blur!", quill);
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      console.log("editor focus!", quill);
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      console.log("editor ready!", quill);
    },
    // 内容改变事件
    onEditorChange({ quill, html, text }) {
      console.log("editor change!", quill, html, text);
      this.content = html;
    },

    newNotice() {
      newNotice(this.announcement).then((response) => {
        if (response.code === 20000) {
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.centerDialogVisible = false;
          this.getNoticeList();
          this.resetData();
        } else {
          this.$message({
            message: "新增失败",
            type: "error",
          });
        }
      });
    },
    updateNotice() {
      updateNotice(this.announcement).then((res) => {
        if (res.code === 20000) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.id = "";
          this.centerDialogVisible = false;
          this.getNoticeList();
          this.resetData();
        } else {
          this.$message({
            message: "修改失败",
            type: "error",
          });
        }
      });
    },

    save() {
      if (this.id === "") {
        this.newNotice();
      } else {
        this.updateNotice();
      }

      this.fileList = [];
    },

    getTokenFromCookie() {
      const cookies = document.cookie.split("; ");
      const token = cookies
        .find((row) => row.startsWith("token="))
        ?.split("=")[1];
      return token;
    },
    // 设置 headers
    setHeaders() {
      this.headers = {
        token: this.getTokenFromCookie(),
      };
    },

    handleRemove() {
      this.announcement.image = "";
      this.onloadfile = 1;
    },

    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },

    mod(row) {
      if (row === 1) {
        this.resetData();
        this.id = "";
      }
      this.centerDialogVisible = true;
      this.$nextTick(() => {
        //赋值到表单
        if (row !== 1) {
          this.id = row.id;
        }
        this.announcement.id = row.id;
        this.announcement.title = row.title;
        this.announcement.content = row.content;
        this.announcement.image = row.image;
        this.announcement.clubId = row.clubId;
        if (row !== 1) {
          this.announcement.isTop = row.isTop;
        }
      });
    },

    deleteNotice(id) {
      deleteNotice(id).then((res) => {
        if (res.code === 20000) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getNoticeList();
        } else {
          this.$message({
            message: "删除失败",
            type: "error",
          });
        }
      });
    },

    // 获取通知列表
    getNoticeListhh() {
      this.page = 1;
      this.getNoticeList();
    },

    getNoticeList() {
      getNoticeList(this.page, this.limit, this.queryVo).then((response) => {
        this.noticeData = response.data.list.records;
        this.total = response.data.list.total;
        this.queryVo.value = "";
      });
    },

    resetData() {
      this.announcement = {
        id: "",
        title: "",
        content: "",
        image: "",
        clubId: "",
        isTop: false,
      };
    },

    // 重置查询条件
    resetQuery() {
      this.queryVo = {
        value: "",
      };
      this.page = 1;
      this.getNoticeList();
    },
    // 改变每页显示数量
    onSizeChange(size) {
      this.noticeData = [];
      this.limit = size;
      this.getNoticeList();
    },
    // 改变当前页
    onCurrentChange(page) {
      this.noticeData = [];
      this.page = page;
      this.getNoticeList();
    },
    //点击查看详细
    inDetail(data) {
      this.postDetails = data;
      this.inDetailDialogVisible = true;
    },
  },
  created() {
    this.setHeaders();
    this.getNoticeList();
  },
  mounted() {
    this.$refs.myInput.focus();
  },
};
</script>

<style>
.center {
  display: flex;
}

.profiletwo {
  margin-left: 2px;
  margin-bottom: 5px;
  display: flex;
  background-color: #fff;
  color: #505050;
  font-size: 18px;
}
.ql-editor {
  box-sizing: border-box;
  line-height: 1.42;
  height: 200px;
  outline: none;
  overflow-y: auto;
  padding: 12px 15px;
  -o-tab-size: 4;
  tab-size: 4;
  -moz-tab-size: 4;
  text-align: left;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
img {
  width: 50%;
}

.el-table .cell {
  display: flex;
  justify-content: center;
    box-sizing: border-box;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
    word-break: break-all;
    line-height: 23px;
    padding-left: 10px;
    padding-right: 10px;
}
</style>
